/**
 * Created by apple on 16/3/31.
 */
"use strict";
import template from './corpEdit.view.html';
import appointList from './specify/appointList.view.html';
import appointListController from './specify/appointList.controller';
import createController from './corpCreate.controller';
import viewController from './corpEdit.controller';

class Controller {
    constructor (systemService, statusMap, CodeText, uiNotification, $uiModal, $stateParams, $state, $timeout, localStorageService, $location) {
        "ngInject"
        this.activeId   = $stateParams.tab || 'info';
        this.notify     = uiNotification;
        this.uiModal    = $uiModal;
        this.timeout    = $timeout;
        this.isEdit     = false;
        this.breadcrumb = localStorageService.get('corp.path');
        this.codeText   = CodeText;
        this.service    = systemService;
        this.localstore = localStorageService;
        this.status        = statusMap;
        this.state         = $state;
        this.stateParam    = $stateParams;
        this.orgId         = $stateParams.id;
        this.pid           = $stateParams.pid;
        this.location      = $location;
        this.postList      = [];
        this.staffList     = [];
        this.userList      = [];
        this.postRecord    = [];
        this.staffRecord   = [];
        this.userRecord    = [];
        this.postAuth      = [];
        this.userAuth      = [];
        this.roleAuth      = [];
        this.dataList      = [];
        this.postClass     = {orgId: "管理岗位", rzOrgId: "任职岗位"}
        this.postSelect    = "orgId"
        this.postClassText = "管理";
        this.postType      = {0: "编码", 1: "名称", 2: "机构"};
        this.staffType     = {0: "编码", 1: "账号", 2: "名称"};
        this.userType      = {0: "账号", 1: "手机", 3: "系统"};
        this.paginate      = {post: {}, user: {}, staff: {}}
        this.page          = {
            post : {},
            staff: {},
            user : {}
        }
        this.search        = {
            post : {q: "", k: "0", txt: "按" + this.postType[ 0 ] + "搜索"},
            staff: {q: "", k: "0", txt: "按" + this.staffType[ 0 ] + "搜索"},
            user : {q: "", k: "0", txt: "按" + this.userType[ 0 ] + "搜索"}
        }
        this.checkedItem   = {};


        systemService.getItem('org', {
            orgId: this.orgId
        }).then((res) => {
            this.isCorpLoad = true;
            this.data = {
                orgId      : this.orgId,
                parentOrgId: res.data.parentOrgId,
                orgCode    : res.data.orgCode,
                orgName    : res.data.orgName,
                orgType    : res.data.orgType,
                updateDate : res.data.updateDate,
                createDate : res.data.createDate,
                statusCd   : res.data.statusCd
            }
            localStorageService.set('corp.info', this.data)
        })
    }

    checkValid (field) {
        if ( field.$pristine ) {
            field.$pristine = false;
        }
    }

    /* 组织信息编辑逻辑 开始 */
    openCorpEdit () {
        this.isEdit = !this.isEdit;
    }

    saveCorp (cancel) {
        if (cancel) {
            this.data = this.localstore.get('corp.info');
            this.isEdit = false;
            return;
        }

        if ( this.submitting ) return;

        this.submitting = true;

        this.service.update('org', this.data).then(() => {
            this.localstore.set('corp.info', this.data);
            this.notify.success({
                'title'  : '提示',
                'message': '操作成功!'
            });
        }).catch((data) => {
            this.data = this.localstore.get('corp.info');
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + data.resultCode == 1062 ? this.codeText.org : (data.resultMsg ? data.resultMsg : "")
            });
        }).finally(() => {
            // 隐藏 loading
            this.isEdit     = false;
            this.submitting = false;
        });
    }

    /* 组织信息编辑逻辑 结束 */

    /* 表格数据操作 */

    openView (type, item, size) {
        let modalInstance = this.uiModal.open({
            animation   : true,
            templateUrl : template,
            controller  : viewController,
            controllerAs: 'vm',
            size        : size || 'md',
            resolve     : {
                type: () => {
                    return type
                },
                plat: () => {
                    return this.service.getPlat()
                },
                item: () => {
                    return item
                }
            }
        });

        // 处理对话框提交/关闭
        modalInstance.result.then((res) => {
            let idx                          = _.findIndex(this[ res.type + 'List' ], {id: res.item.id});
            this[ res.type + 'List' ][ idx ] = res.item;
            //this.load(res, true)
        });
    }

    openCreate (type, size) {
        this.notify.clearAll();
        if ( type == 'user' && this[ type + "Auth" ].length == 0 ) {
            return this.notify.error({
                'title'  : '提示',
                'message': '至少选择一条数据!'
            });
        }
        let modalInstance = this.uiModal.open({
            animation   : true,
            templateUrl : template,
            controller  : createController,
            controllerAs: 'vm',
            size        : size || 'md',
            resolve     : {
                type: () => {
                    return type
                },
                plat: () => {
                    return this.service.getPlat()
                },
                item: () => {
                    return this.checkedItem
                }
            }
        });
        modalInstance.result.then(() => {
            this.load(type, true)
        });
    }

    openAppoint (type, classify, size) {
        this.notify.clearAll();
        if ( this[ classify + 'Auth' ].length == 0 ) {
            return this.notify.error({
                'title'  : '提示',
                'message': '至少选择一条数据!'
            });
        }
        let modalInstance = this.uiModal.open({
            animation   : true,
            templateUrl : appointList,
            controller  : appointListController,
            controllerAs: 'vm',
            size        : size || 'lg',
            resolve     : {
                node: () => {
                    return {
                        context : this.checkedItem,
                        checkId : this[ classify + 'Id' ],
                        type    : type,
                        classify: classify,
                    }
                }
            }
        });
        modalInstance.result.then(() => {

        });
    }

    toggleCheck (type, item) {
        __DEBUG__ && console.log(item)
        //item.checked = !item.checked;
        let idx = _.findIndex(this[ type + "Auth" ], {id: item.id});

        if ( idx == -1 ) {
            this[ type + "Auth" ] = item;
        }

        this.checkedItem    = item;
        this[ type + 'Id' ] = item[ 'sys' + type.replace(type.charAt(0), function (s) {
            return s.toUpperCase();
        }) + "Id" ];
        angular.extend(this.stateParam, {
            cur: type == "post" ? item.sysPostName : item.sysUserCode
        })
    }

    toggleConfirm (item) {
        item.confirm = !item.confirm;
    }

    del (type, id) {

        let param = type == 'post' ? {sysPostId: id} : type == 'staff' ? {staffId: id} : {sysUserId: id};

        this.service
            .delItem(type, param)
            .then(() => {
                this[ type + 'List' ].splice(_.findIndex(this[ type + 'List' ], {id: id}), 1);
                this.notify.success({
                    'title'  : '提示',
                    'message': '操作成功!'
                });
            }).catch((data) => {

            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
            });
        })
    }

    load (type, force, postSelect) {
        //this.stateParam.tab       = type;
        this.page[ type ].perPage = 8;
        // this.page[type].currentPage = this.location.search().page;
        if ( this[ type + 'List' ] && this[ type + 'List' ].length && !force ) return;
        let tempType                  = type.replace(type.charAt(0), (s) => {
            return s.toUpperCase()
        })
        let param                     = postSelect == "rzOrgId" ? {rzOrgId: this.orgId} : {orgId: this.orgId}
        this.page[ type ].currentPage = this.stateParam.page ? this.stateParam.page : 1;
        if ( type == "post" && postSelect ) {
            this.isPostLoad      = false;
            this.postList.length = 0
        }
        this.service
            .getList(type, param, this.page[ type ])
            .then(res => {
                this[ 'is' + tempType + 'Load' ] = true;
                this[ type + 'List' ]            = res.data.list;
                this[ type + 'Record' ]          = res.data.list;
                this.paginate[ type ].totalItems = res.data.list.length;
                this.page[ type ].totalItems     = res.data.total;
                // 是否分页
                __DEBUG__ && console.log(res.data.total, this.page[ type ].perPage, this.page[ type ].currentPage)
                this.hasPager = ( res.data.total > this.page[ type ].perPage ) ? true : false;
            }).catch((data) => {
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + data.resultCode == 1062 ? this.codeText.org : (data.resultMsg ? data.resultMsg : "")
            });
        }).finally(() => {
            // 隐藏 loading
            this[ 'is' + tempType + 'Load' ] = true;
        });
    }

    /**
     * 权限设置
     * @param type
     * @returns {*}
     */
    makeAuth (type) {
        this.notify.clearAll();
        if ( this[ type + "Auth" ].length == 0 ) {
            return this.notify.error({
                'title'  : '提示',
                'message': '至少选择一条数据!'
            });
        }
        console.log(this[ type + "Auth" ])
        // 当前用户|岗位 id
        angular.extend(this.stateParam, {
            core: this[ type + 'Id' ]
        })
        this.state.go(type + '/auth', this.stateParam);
    }

    changeType (type) {
        this.search[ type ].txt = "按" + this[ type + 'Type' ][ this.search[ type ].k ] + "搜索"
    }

    changePost () {
        this.postSelect == "orgId" ? this.postClassText = "管理" : this.postClassText = "任职"
        this.load('post', true, this.postSelect)
    }

    toSearch (type, param) {
        this[ type + 'Searching' ] = true;
        this.service
            .getList(type, param)
            .then((res) => {
                __DEBUG__ && console.log(res)
                if ( res.data.total < this.page.perPage ) {
                    this[ type + "Pager" ] = false;
                }
                if ( res.data.total == 0 ) {
                    this[ type + 'NoData' ] = false;
                }
                this[ type + 'List' ] = res.data.list;
            }).finally(() => {
            this[ type + 'Searching' ] = false;
        })
    }

    makeSearch (type, $event) {
        if ( this[ type + 'Searching' ] ) return;

        if ( this.search[ type ].q == "" ) {
            this[ type + 'List' ]      = this[ type + 'Record' ];
            this[ type + 'Searching' ] = false;
            this[ type + 'NoData' ]    = false;
            return;
        }

        let param = {
            orgId: this.orgId
        };

        if ( type == 'post' ) {
            switch ( this.search[ type ].k ) {
                case "0":
                    param.sysPostCode = this.search[ type ].q;
                    break;
                case "1":
                    param.sysPostName = this.search[ type ].q;
                    break;
                case "2":
                    param.sysPostName = this.search[ type ].q;
                    break;
            }
        }
        if ( type == 'staff' ) {
            switch ( this.search[ type ].k ) {
                case "0":
                    param.staffCode = this.search[ type ].q;
                    break;
                case "1":
                    param.staffAccount = this.search[ type ].q;
                    break;
                case "2":
                    param.staffName = this.search[ type ].q;
                    break;
            }
        }
        if ( type == 'user' ) {
            switch ( this.search[ type ].k ) {
                case "0":
                    param.sysUserCode = this.search[ type ].q;
                    break;
                case "1":
                    param.sysUserName = this.search[ type ].q;
                    break;
                case "2":
                    param.sysCode = this.search[ type ].q;
                    break;
            }
        }

        if ( $event ) {
            if ( $event.keyCode !== 13 ) return;
            return this.toSearch(type, param)
        }
        this.toSearch(type, param);
    }

    changePage (type, currentPage, postSelect) {
        let param = postSelect == "rzOrgId" ? {rzOrgId: this.orgId} : {orgId: this.orgId}
        this.location.search('page', currentPage);
        this.service.getList(type, param, this.page[ type ]).then((res) => {
            this[ type + 'List' ] = res.data.list;
        })
    }

}

export default Controller;